package com.Renderer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import com.Core.GameEngine;
import com.Core.GameLogic;
import com.Object.ObjType;
import com.Object.SeaObject;

import android.opengl.GLSurfaceView.Renderer;

public class MainRenderer implements Renderer
{	private long loopStart = 0;
	private long loopEnd = 0;
	private long loopRunTime = 0;
	private GameBackground background;
	private GameField playfield;
	private GameLogic logic;
	
	public MainRenderer()
	{	background = new GameBackground();
		playfield = new GameField();
		logic = GameEngine.logic;
	}
	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config)
	{	gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glClearDepthf(1.0f);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		
		background.loadTexture(gl, GameEngine.globalContext);
		playfield.loadTexture(gl, GameEngine.globalContext);
	}
	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height)
	{	gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		
		if (height>width)
		{	GameEngine.pjRight	= GameEngine.UP_BOUND;
			GameEngine.pjTop	= GameEngine.FIELD_LENGTH*height/width-0.5f;
		}
		else
		{	GameEngine.pjTop	= GameEngine.UP_BOUND;
			GameEngine.pjRight	= GameEngine.FIELD_LENGTH*width/height-0.5f;
		}
		gl.glOrthof
		(	GameEngine.pjLeft	, GameEngine.pjRight,
			GameEngine.pjBottom	, GameEngine.pjTop	,
			GameEngine.pjNear	, GameEngine.pjFar
		);
		background.SuggestOrientation();
	}
	@Override
	public void onDrawFrame(GL10 gl)
	{	loopStart = System.currentTimeMillis();
		try
		{	if (loopRunTime < GameEngine.GAME_FPS_SLEEP)
				Thread.sleep(GameEngine.GAME_FPS_SLEEP-loopRunTime);
		}
		catch (InterruptedException e)
		{	e.printStackTrace();
		}
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT|GL10.GL_DEPTH_BUFFER_BIT);
		
		logic.CheckAniForCurPos();
		background.draw(gl);
	//	GameEngine.curObj = SeaObject.CreateObject(ObjType.Ship);
		playfield.draw(gl);
		playfield.drawOverlay(gl);
		
		loopEnd = System.currentTimeMillis();
		loopRunTime = loopEnd-loopStart;
	}
}
